import qrcode
import win32print
import win32ui
from PIL import Image, ImageWin

def generate_qrcode(text, filename):
    qr = qrcode.QRCode(
        version=1,
        error_correction=qrcode.constants.ERROR_CORRECT_L,
        box_size=10,
        border=4,
    )
    qr.add_data(text)
    qr.make(fit=True)

    img = qr.make_image(fill_color="black", back_color="white")
    img.save(filename)

def print_image(filename):
    # 打开默认打印机
    printer_name = win32print.GetDefaultPrinter()
    hPrinter = win32print.OpenPrinter(printer_name)
    
    # 获取打印机设备上下文
    hDC = win32ui.CreateDC()
    hDC.CreatePrinterDC(printer_name)

    # 设置打印文档的宽高
    bmp = Image.open(filename)
    dib = ImageWin.Dib(bmp)
    
    # 开始打印任务
    win32print.StartDocPrinter(hPrinter, 1, ("QR Code", None, "RAW"))
    win32print.StartPagePrinter(hPrinter)

    # 将图像绘制到打印机设备上下文
    hDC.StartDoc("QR Code")
    hDC.StartPage()
    
    # 计算打印区域大小并绘制图像
    dib.draw(hDC.GetHandleOutput(), (0, 0, bmp.size[0], bmp.size[1]))
    
    # 结束打印页面和文档
    hDC.EndPage()
    hDC.EndDoc()

    win32print.EndPagePrinter(hPrinter)
    win32print.EndDocPrinter(hPrinter)
    win32print.ClosePrinter(hPrinter)

if __name__ == "__main__":
    while True:
        text_to_encode = input("输入字符生成二维码并打印 (输入 exit 退出程序): ")

        # 允许用户输入 'exit' 来退出程序
        if text_to_encode.lower() == 'exit':
            print("退出程序.")
            break

        output_filename = "qrcode.png"
        
        # 生成二维码并打印
        generate_qrcode(text_to_encode, output_filename)
        print("二维码创建成功.")

        print("打印二维码中...")
        print_image(output_filename)

        print("二维码打印成功, 等待输入...")
